<?php

class Admin_MatriculaController extends App_Controller_Action
{
    private $_table     = 'MATRICULA';
    private $_pk        = 'MAT_ID';
    private $_order_col = 'MAT_ID';
    private $_order     = 'ASC';
    private $_sta_col   = 'MAT_STA';
    private $obj        = '';
    private $form       = '';
    public  $db = '';
    
    public function init()
    {
        $this->obj = new Admin_Model_DbTable_Matricula();
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Matricula();
        $this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('operacoes','library');
        Zend_Loader::loadClass('elemform','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_matricula_list.js?1=7');
        
        $where = '';//$this->_pk . ' > 0';
        
        $stfiltro = $this->_getParam('stfiltro', '1');
        $itfiltro = $this->_getParam('itfiltro', '');
        
        
        if($stfiltro != '') $where .= ' and m.MAT_STA = ' . $stfiltro;
        if($itfiltro != '') $where .= ' and m.CUR_ID = ' . $itfiltro;
        
        $this->view->stfiltro = $stfiltro;
        $this->view->itfiltro = $itfiltro;
        
        $filtro_nm = $this->_getParam('filtro_nm', '');
        $filtro_an = $this->_getParam('filtro_an', '');
        $filtro_tr = $this->_getParam('filtro_tr', '');
        
        if($filtro_nm != '') $where .= ' and a.ALU_NOM like "%' . trim($filtro_nm).'%"';
        if($filtro_an != '') $where .= ' and c.CUR_ANO = ' . $filtro_an.' ';
        if($filtro_tr != '') $where .= ' and m.CUR_ID = ' . $filtro_tr.' ';
        
        $this->view->filtro_nm = $filtro_nm;
        $this->view->filtro_an = $filtro_an;
        $this->view->filtro_tr = $filtro_tr;
        
        
        $query = 'SELECT SQL_CACHE m.MAT_ID, m.MAT_DATHOR, a.ALU_ID, a.ALU_NOM, c.CUR_ID '
                .' FROM '.$this->_table.' m, ALUNO a, CURSO c, CURSOBASE b '
                .' WHERE m.ALU_ID = a.ALU_ID AND m.CUR_ID = c.CUR_ID '
                .' AND c.CBS_ID = b.CBS_ID '
                .' '.$where.' '
                .' ORDER BY m.'.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result,20);
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_matricula.js?1='.rand(9,99999));
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_aluno_popup.js'); 
        
        //$this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_aluno.js');
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('operacoes','library');
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                
                
                $this->db->beginTransaction();
                $mat = $this->verificamatriculaaluno($formData['ALU_ID'],$formData['CUR_ID']);
                if($mat == false){ 
                    $id = (int) $formData[$this->_pk];
                    
                    $data = $formData;
                    
                    unset($data['submit']);
                    
                    // limpa variáveis
                    unset($data['USU_NOME']);
                    unset($data['_user']);
                    unset($data['_key']);
                    unset($data['CUR_VLR']);
                    unset($data['ALU_NOM']);
                    unset($data['CUR_VLRPRO']);
                    unset($data['CUR_DATPRO']);
                    unset($data['CUR_PERDSC']);
                    $cur_val = 0;
                    
                    $data['MAT_STA'] = 1;
                    
                    // recupera curso
                    $query = 'SELECT SQL_CACHE * FROM CURSO WHERE CUR_ID = '. (int) $data['CUR_ID'];
                    $r_cur = $this->db->fetchRow($query);
                    
                    // recupera forma pagamento
                    $query = 'SELECT SQL_CACHE * FROM FORMAS_PAGAMENTO WHERE FOR_ID = '. (int) $data['FOR_ID'];
                    $for_pag = $this->db->fetchRow($query);
                    
                    $data['MAT_STABOL'] = (int) $for_pag['FOR_STABOL'];
                    $data['MAT_VLRENT'] = tools::money_to_float($data['MAT_VLRENT']);
                    
                    $sem = $r_cur['CUR_TPOTMP'];
                    $max_vagas = $r_cur['CUR_NMRMAXALU'];
                        
                    $data['MAT_DATHOR'] = date('Y-m-d H:i:00');
                    $data['MAT_VLR'] = $r_cur['CUR_VLR'];
                    $data['MAT_VLRPRO'] = 0;
                    $data['MAT_STADIR'] = 0;
                    $datapro = strtotime($r_cur['CUR_DATPRO']);
                    $hoje = strtotime(date("Y-m-d"));
                    if($datapro >=  $hoje){
                        $data['MAT_VLRPRO'] = $r_cur['CUR_VLRPRO'];
                        $data['MAT_DATPRO'] = $r_cur['CUR_DATPRO'];
                        $cur_val = $data['MAT_VLRPRO'];
                    }
                   
                    
                    $data['MAT_VLRDIR'] = tools::money_to_float($data['MAT_VLRDIR']);
                    if((int)$data['MAT_VLRDIR'] > 0){
                        $user = addslashes($formData['_user']);
                        $key = addslashes($formData['_key']);
                        $obj = new Admin_Model_DbTable_Usuarios();
                        $res = $obj->fetchRow('USU_LOGIN = "' . $user.'" and USU_SENHA = "'.sha1($key).'"');

                        if($res['USU_ID'] > 0 && $res['USU_LOGIN'] == $user && $res['USU_SENHA'] == sha1($key)){
                            $data['USU_IDADM'] = $user;
                            $data['USU_SNHADM'] = sha1($key);
                            $data['MAT_STADIR'] = 1;
                            $cur_val = $data['MAT_VLRDIR'];
                        }
                        else{
                            $data['MAT_VLRDIR'] = 0;
                        }
                    }
                        
                     
                    if ($id == 0){ 
                        
                        $vaga = Operacoes::vagasCurso($data['CUR_ID']);
                    
                        if($vaga <= 0) // fila de espera para matricula
                            $data['MAT_STA'] = 0;
                        
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId(); 
                        
                        if($vaga <= 0) {
                            // fila de espera
                            $fil = new Admin_Model_DbTable_Filamatricula();
                            $data_fil = array('MAT_ID'=>$id, 'CUR_ID'=>$data['CUR_ID']);
                            $fil->insert($data_fil);
                        } else {
                            
                            // verifica e lança conteudo para o aluno
                            $this->verificatopicoparaaluno($data['ALU_ID'],$data['CUR_ID']);
                            
                            // verifica e lança lista de teste
                            $this->verificalistaparaaluno($data['ALU_ID'],$data['CUR_ID']);
                            
                            // gera as parcelas
                            $mat = new Admin_Model_DbTable_Parcelamento();
                            $par = array();
                            $datamat = dominio::getDataMatricula();
                            
                            if($cur_val == 0) $cur_val = $data['MAT_VLR'];
                            
                            //echo ' 1 - '.$cur_val;
                            
                            //entrada
                            if((int) $data['MAT_VLRENT'] > 0) $cur_val = $cur_val - $data['MAT_VLRENT'];
                            
                            //echo ' 2 - '.$cur_val;
                            
                            $valor_total = 0;
                            
                            // qtd parcelas
                            $parcelas = $data['MAT_QTDPAR'];
                            
                            // a vista desconto, uma parcela e não valor promocional
                            if((int)$for_pag['FOR_STAPAR'] == 0 && $data['MAT_STADIR'] == 0){
                                $cur_val = $cur_val - (($cur_val * $r_cur['CUR_PERDSC']) / 100);
                            }
                            
                            //echo ' 3 - p '.$parcelas.' - '.$r_cur['CUR_PERDSC'].' - '.$cur_val;
                            
                            if($parcelas > 0)
                            for($i = 1; $i <= $parcelas; $i++){

                                $valor = tools::trunc_valor($cur_val / $data['MAT_QTDPAR']);
                                if($i == $data['MAT_QTDPAR']) $valor = $cur_val - $valor_total;
                                $valor_total += $valor;

                                $par['MAT_ID'] = $id;
                                $par['PAR_NUM'] = $i;
                                $par['PAR_DAT'] = date('Y-m-d', mktime(0, 0, 0, date('m') + $i, $datamat[$sem]['d'], date('Y') ));
                                $par['PAR_STA'] = 1;
                                $par['PAR_VLR'] = $valor;
                                $par['FOR_ID'] = $data['FOR_ID'] > 0 ? $data['FOR_ID']:4;
                                $mat->insert($par);
                            }
                            
                            // enviar email
                            
                            $query = 'SELECT SQL_CACHE u.* FROM USUARIOS u, ALUNO a '
                                    .' WHERE u.USU_ID = a.USU_ID AND a.ALU_ID = '.$data['ALU_ID'];
                            $row = $this->db->fetchRow($query);
                            if($row['USU_CADSTA'] == '2'){
                                // nova senha
                                Zend_Loader::loadClass('usuario','library');
                                $senha = Usuario::gerarSenhaUsuario();
                                
                                Zend_Loader::loadClass('envioemail','library');
                                $arr['nome'] = $row['USU_NOME'];
                                $arr['email'] = $row['USU_EMAIL'];
                                $arr['usuario'] = $row['USU_LOGIN'];
                                $arr['senha'] = $senha;
                                $arr['urlbase']  = $this->_urlbase;
                                
                                $ok = envioemail::emailMatriculaSenha($arr);
                                
                                if($ok){
                                    $user = array();
                                    $user['USU_CADSTA'] = 1;
                                    $user['USU_SENHA'] = sha1($senha);
                                    $this->db->update('USUARIOS', $user,'USU_ID = '.$row['USU_ID']);
                                }
                            }
                        }
                        
                    } 
                    else {
                        
                        if($data['CUR_ID'] <= ''){
                            $query = 'SELECT SQL_CACHE CUR_ID FROM '.$this->_table.' WHERE MAT_ID = '. $data['MAT_ID'];
                            $r_cur = $this->db->fetchRow($query);
                            
                            $data['CUR_ID'] = $r_cur['CUR_ID'];
                        }
                        // verifica e lança conteudo para o aluno
                        $this->verificatopicoparaaluno($data['ALU_ID'],$data['CUR_ID']);

                        // verifica e lança lista de teste
                        $this->verificalistaparaaluno($data['ALU_ID'],$data['CUR_ID']);
                        
                        $data = array(
                            'MAT_STA' => $formData['MAT_STA'],
                        );
                        
                        $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                        
                    }
                    
                    $this->db->commit();
                        
                    $this->_helper->redirector('index');
                    
                } else {
                    $formData['MAT_VLRDIR'] = 0;
                    //$this->form->populate($formData);
                    $this->view->data = $formData;
                    echo '<script> alert("Aluno já possui uma matricula no Curso!"); </script>';
                    $this->db->rollBack();
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->view->data = $formData;
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->obj->fetchRow($this->_pk . ' = ' . $id)->toArray();
                
                $obj2 = new Admin_Model_DbTable_Aluno();
                $alu = $obj2->fetchRow('ALU_ID = ' . $data['ALU_ID'])->toArray();
                $data['ALU_NOM'] = $alu['ALU_NOM'];
                
                $obj2 = new Admin_Model_DbTable_Curso();
                $cur = $obj2->fetchRow('CUR_ID = ' . $data['CUR_ID'])->toArray();
                $data['CUR_VLR'] = tools::float_to_money($cur['CUR_VLR']);
                //$this->form->populate($data);
                
                $obj2 = new Admin_Model_DbTable_Usuarios();
                $usu = $obj2->fetchRow('USU_ID = ' . $data['USU_ID'])->toArray();
                $data['USU_NOME'] = $usu['USU_NOME'];
                
                $this->view->data = $data;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $error = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        $per = $this->_getParam('per', 0);
        if ((int)$id > 0 ) {   
            //$par = new Admin_Model_DbTable_Parcelamento;
            //$r_par = $par->fetchRow($this->_pk . ' = ' . $id.' and PAR_STA = 1 and PAR_STAPGO = 1');
            //if($r_par['MAT_ID'] <= 0 || $per == 1){
                
                $data = array($this->_sta_col => 0);
                $ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);

                //$ok = (bool) $par->update(array('PAR_STA' => 0), $this->_pk . ' = ' . $id);
            //}
            //else{
            //    $error = TRUE;
            //    $msg = 'Matrícula possui pagamentos realizados. Deseja realmente excluir?';
            //}
            
        }      
        //$this->_helper->redirector('index');
        echo json_encode(array('ok' => $ok, 'url' => '' ,'error' => $error, 'msg' => $msg));
    }
    
    public function cursodadosAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('operacoes','library');
        $ok = TRUE;
        $valor = 0;
        $valorpro = 0;
        $html_for = ''; 
        
        $id = $this->_getParam('cur_id', 0);
        if($id > 0){
            $obj = new Admin_Model_DbTable_Curso();
            $row = $obj->fetchRow('CUR_ID = ' . $id)->toArray();
            $valor = tools::float_to_money($row['CUR_VLR']);
            $sem = $row['CUR_TPOTMP'];
            $datapro = strtotime($row['CUR_DATPRO']);
            $hoje = strtotime(date("Y-m-d"));
            if($datapro >=  $hoje)
                $valorpro = tools::float_to_money($row['CUR_VLRPRO']);
            $nvaga = Operacoes::vagasCurso($row['CUR_ID']);
            if((int) $nvaga <= 0) $vagas = false;
            else $vagas = true;
            
            // forma pagamento
            $forc = new Admin_Model_DbTable_Cursoforma();
            $forc = $forc->fetchAll('CUR_ID = '.$id);
            $html_for .= '<option value="">Nenhum</option>'; 
            foreach($forc as $f)
            {   
                $for = new Admin_Model_DbTable_Formaspagamento();
                $for = $for->fetchRow('FOR_ID = '.$f['FOR_ID']);
                $html_for .= '<option value="'.$for['FOR_ID'].'">'.$for['FOR_NOM'].'</option>';
            }
            echo json_encode(array('ok'=>$ok,'valor'=>$valor, 'valorpro'=>$valorpro, 'vagas'=>$vagas, 'for'=>$html_for));
        }
        else{
            echo json_encode(array('ok'=>true,'valor'=>'', 'valorpro'=>'', 'vagas'=>true, 'for'=>''));
        }
    }
        
    public function tipopagAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
        $ok = TRUE;
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('operacoes','library');
        
        $numparc = 0;
        $id = $this->_getParam('cur_id', 0);
        $for_pag = $this->_getParam('for_pag', 0);
        $vlr_desc = 0;
        if($id > 0 && $for_pag > 0){
            $obj = new Admin_Model_DbTable_Curso();
            $row = $obj->fetchRow('CUR_ID = ' . $id)->toArray();
            $valor = tools::float_to_money($row['CUR_VLR']);
            $sem = $row['CUR_TPOTMP'];
            $ano = $row['CUR_ANO'];
            
            $obj = new Admin_Model_DbTable_Formaspagamento();
            $row2 = $obj->fetchRow('FOR_ID = ' . $for_pag)->toArray();
            
            $staparc = $row2['FOR_STAPAR'];
            if($staparc == 1){
                $numparc = Operacoes::getNumParcSem($sem,$ano);
            }else{
               $numparc = 1; 
               $vlr_desc = tools::float_to_money($row['CUR_PERDSC']);
            }   
            
        }
        else if($for_pag > 0){
            $ok = false;
            $msg = 'Selecione um curso!';   
        }
        
        
        echo json_encode(array('ok'=>$ok,'msg'=>$msg,'parcelas' => $numparc, 'vlr_desc'=>$vlr_desc));
    } 
    
    public function libacessoAction(){
        $this->_helper->layout->disableLayout(); 
        $op = $this->_getParam('op', '');
        if($op == 'valid'){
            $this->_helper->viewRenderer->setNoRender();
            
            $user = addslashes($this->_getParam('user',''));
            $key = addslashes($this->_getParam('key',''));

            $obj = new Admin_Model_DbTable_Usuarios();
            $res = $obj->fetchRow('USU_LOGIN = "' . $user.'" and USU_SENHA = "'.sha1($key).'" and PER_ID = 1 ');
            
            if($res['USU_ID'] > 0 && $res['USU_LOGIN'] == $user && $res['USU_SENHA'] == sha1($key)){
                echo json_encode(array('ok'=>true));
            }
            else echo json_encode(array('ok'=>false));
        }
    }
    
    public function verificamatriculaalunoAction(){
        Zend_Loader::loadClass('dominio','library');
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
        $ok = false;
        $msg = '';
        $id = $this->_getParam('id', 0);
        $cur_id = $this->_getParam('cur_id', 0);
        
        if($id > 0 && $cur_id > 0){
            //$data = $this->obj->fetchRow('MAT_STA = 1 and ALU_ID = ' . $id);
            //if(isset($data->MAT_ID) && $data->MAT_ID > 0){
            $ok = $this->verificamatriculaaluno($id,$cur_id);
            if($ok == true){
                //$ok = true;

                $query = ' SELECT SQL_CACHE c.CUR_ID '
                        .' FROM CURSO c, MATRICULA m '
                        .' WHERE m.ALU_ID = '.$id
                        .' AND c.CUR_ID = m.CUR_ID'
                        .' AND c.CUR_ANO = "'.date('Y').'"'
                        .' AND c.CUR_STA = 1 AND m.MAT_STA = 1';
                $cur = $this->db->fetchRow($query);

                $msg = "Aluno já possui uma matricula no \nCurso ".dominio::getTurma($cur['CUR_ID'],0).'!';
            }
        }
        
        echo json_encode(array('ok'=>$ok, 'msg' => $msg));
    }
    
    public function verificamatriculaaluno($id = 0,$cur_id = 0){
        $ok = false;
        $query = ' SELECT SQL_CACHE MAT_ID '
                .' FROM '.$this->_table.' '
                .' WHERE MAT_STA = 1 and ALU_ID = ' . $id
                ;//.' AND CUR_ID = '.$cur_id;
        $row = $this->db->fetchRow($query); 
        if($row['MAT_ID'] > 0){
            $ok = true;
        }    
        return $ok;
    }
    
    
    public function filtroturmasAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
        Zend_Loader::loadClass('dominio','library');
        $ok = true;
        $html = '<option value="">Turma</option>';
        $ano = $this->_getParam('ano', 0);
        
        $where = '';
        if($ano > 0){ 
            $where = 'WHERE CUR_ANO = '.$ano.'';
        }
        
        $query = 'SELECT SQL_CACHE CUR_ID FROM CURSO '.$where.' ORDER BY CUR_ANO DESC';
        $f_cur = $this->db->fetchAll($query);

        foreach($f_cur as $r){   
            $html .= '<option value="'.$r['CUR_ID'].'">'.dominio::getTurma($r['CUR_ID'],0).'</option>';
        }
        
        
        echo json_encode(array('ok' => $ok,'html'=>$html));
    }
    
    public function verificatopicoparaaluno($alu_id = 0,$cur_id = 0){
        
        $flag = 0;
        
        if($alu_id > 0 && $cur_id > 0){
            
            $query = 'SELECT SQL_CACHE CBS_ID FROM CURSO WHERE CUR_ID = '.$cur_id.' AND CUR_STA = 1 ';
            $result = $this->db->fetchRow($query);
            $cbs_id = $result['CBS_ID'];

            if($cbs_id > 0){

                $query = 'SELECT SQL_CACHE * FROM PUBLICACAO WHERE CBS_ID like "%'.$cbs_id.'%" AND PBC_STA = 1 ';
                $result = $this->db->fetchAll($query);
                foreach($result as $row){
                    
                    if($row['TPC_ID'] > 0){
                        $arr2 = array(
                            'TPC_ID'  => $row['TPC_ID'],
                            'ALU_ID'  => $alu_id,
                            'PBC_ID'  => $row['PBC_ID'],
                        );

                        if($this->validaTopicoAluno($row['TPC_ID'],$alu_id)){
                            $this->db->insert('TOPICO_ALUNO',$arr2);
                            $flag = 1;
                        }
                    }
                }
            }
            
            if($cbs_id > 0 && $flag == 0){
                $query = 'SELECT SQL_CACHE * FROM PUBLICACAO WHERE CUR_ID like "%'.$cur_id.'%" AND PBC_STA = 1 ';
                $result = $this->db->fetchAll($query);
                foreach($result as $row){
                    
                    if($row['TPC_ID'] > 0){ 
                        $arr2 = array(
                            'TPC_ID'  => $row['TPC_ID'],
                            'ALU_ID'  => $alu_id,
                            'PBC_ID'  => $row['PBC_ID'],
                        );

                        if($this->validaTopicoAluno($row['TPC_ID'],$alu_id)){
                            $this->db->insert('TOPICO_ALUNO',$arr2);
                        }
                    }
                }
            }
        }
        
    }
    
    public function validaTopicoAluno($topico,$aluno) {
        
        $query = 'SELECT SQL_CACHE ALU_ID FROM TOPICO_ALUNO WHERE TPC_ID in('.$topico.') AND ALU_ID = '.$aluno;
        $row = $this->db->fetchRow($query);
        if($row['ALU_ID'] > 0 ) return false;
        else return true;
        
    }
    
     public function verificalistaparaaluno($alu_id = 0,$cur_id = 0){
        
        $flag = 0;

        if($alu_id > 0 && $cur_id > 0){
            
            $query = 'SELECT SQL_CACHE CBS_ID FROM CURSO WHERE CUR_ID = '.$cur_id.' AND CUR_STA = 1 ';
            $result = $this->db->fetchRow($query);
            $cbs_id = $result['CBS_ID'];
            
            if($cbs_id > 0){

                $query = 'SELECT SQL_CACHE PUL_ID FROM PUBLICACAO_LISTA WHERE CBS_ID like "%'.$cbs_id.'%" AND PUL_STA > 0';
                $result = $this->db->fetchAll($query);
                foreach($result as $row){

                    $arr2 = array(
                        'PUL_ID'  => $row['PUL_ID'],
                        'ALU_ID'  => $alu_id,
                    );
                   
                    if($this->validaListaAluno($row['PUL_ID'],$alu_id)){
                        $this->db->insert('PUBLICACAO_LISTA_ALUNO',$arr2);
                        $flag = 1;
                    }
                }
            }
            
            if($cbs_id > 0 && $flag == 0){
                $query = 'SELECT SQL_CACHE PUL_ID FROM PUBLICACAO_LISTA WHERE CUR_ID like "%'.$cur_id.'%" AND PUL_STA > 0';
                $result = $this->db->fetchAll($query);
                foreach($result as $row){

                    $arr2 = array(
                        'PUL_ID'  => $row['PUL_ID'],
                        'ALU_ID'  => $alu_id,
                    );

                    if($this->validaListaAluno($row['PUL_ID'],$alu_id)){
                        $this->db->insert('PUBLICACAO_LISTA_ALUNO',$arr2);
                    }
                }
            }
        }
        
    }
    
    public function validaListaAluno($pul_id,$aluno) {
        
        $query = 'SELECT SQL_CACHE ALU_ID FROM PUBLICACAO_LISTA_ALUNO WHERE PUL_ID = '.$pul_id.' AND ALU_ID = '.$aluno;
        $row = $this->db->fetchRow($query);
        if($row['ALU_ID'] > 0 ) return false;
        else return true;
    }
    
    
    public function corrigirerropublicacoesAction(){
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();
        
        $query = ' SELECT SQL_CACHE DISTINCT(a.ALU_ID), c.CUR_ID '
                .' FROM ALUNO a '
                .' INNER JOIN MATRICULA m ON m.ALU_ID = a.ALU_ID AND MAT_STA = 1 '
                .' INNER JOIN CURSO  c ON c.CUR_ID = m.CUR_ID AND CUR_STA = 1 '
                .' WHERE a.ALU_STA = 1';
        $result = $this->db->fetchAll($query);
        foreach($result as $data){

            // verifica e lança conteudo para o aluno
            $this->verificatopicoparaaluno($data['ALU_ID'],$data['CUR_ID']);

            // verifica e lança lista de teste
            $this->verificalistaparaaluno($data['ALU_ID'],$data['CUR_ID']);
        }
        
    }
    
}

